package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"novel-kit/model/cache"
	"novel-kit/model/mysql"
	"strconv"

	"novel-kit/novelrpc/internal/svc"
	"novel-kit/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 修改密码
func (l *UpdatePasswordLogic) UpdatePassword(in *novelrpc.UpdatePasswordRequest) (*novelrpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	var UserUpdate mysql.User
	if err := UserUpdate.FindUserById(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("用户不存在")
	}

	if err := UserUpdate.FindUserByMobil(mysql.DB, in.Mobile); err != nil {
		return nil, errors.New("手机号不存在")
	}

	if UserUpdate.Password == in.Password {
		return nil, errors.New("密码与原密码一致，禁止修改")
	}

	if in.PasswordAgain != in.Password {
		return nil, errors.New("两次密码不一致")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendsms"+in.Mobile).Result()
	if result != in.SmsCode {
		return nil, errors.New("验证码不正确")
	}

	Users := mysql.User{
		Model:    gorm.Model{},
		Password: in.Password,
	}

	if err := Users.UpdatePassword(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("修改失败")
	}
	return &novelrpc.UpdatePasswordResponse{
		UserId: strconv.Itoa(int(UserUpdate.ID)),
	}, nil
}
